import constantRoutes from "@/router/constantRoutes";
import asyncRoutes from "@/router/asyncRoutes";
import { addRoutes } from "@/router";

/**
 * 判断用户是否有权限访问该路由
 */
function hasPermission(roles, route) {
  // 当前路由需要权限
  if (route.meta && route.meta.roles) {
    return roles.some((role) => route.meta.roles.includes(role));
  }
  // 无需权限
  else {
    return true;
  }
}

/**
 * 根据权限过滤路由列表
 */
export function filterAsyncRoutes(routes, roles) {
  const res = [];

  routes.forEach((route) => {
    const tmp = { ...route };
    // 有权限
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });

  return res;
}

const state = {
  addRoutes: [], // 需添加的路由列表
  routes: [], // 全部可访问的路由列表
};

const mutations = {
  // 设置路由列表
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
};

const actions = {
  // 生成路由列表
  generateRoutes({ commit }, roles) {
    return new Promise((resolve) => {
      // let newRoutes; // 可访问的路由列表
      // if (roles.includes("admin")) {
      //   newRoutes = asyncRoutes || [];
      // } else {
      //   newRoutes = filterAsyncRoutes(asyncRoutes, roles);
      // }
      const newRoutes = asyncRoutes || [];
      // 添加路由
      addRoutes(newRoutes);
      // 设置路由列表
      commit("SET_ROUTES", newRoutes);
      resolve(newRoutes);
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
